﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Application.Service.TwoCategories.Dto;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
namespace Admin.NET.Application;

/// <summary>
/// 报修管理服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class MaintenancesService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Maintenances> _maintenancesRep;
    public MaintenancesService(SqlSugarRepository<Maintenances> maintenancesRep)
    {
        _maintenancesRep = maintenancesRep;
    }

    /// <summary>
    /// 分页查询报修管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询报修管理")]
    public async Task<SqlSugarPagedList<MaintenancesOutput>> Page(PageMaintenancesInput input)
    {
		input.SearchKey = input.SearchKey?.Trim();
        var query = _maintenancesRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.Mnumber.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.Mnumber), u => u.Mnumber.Contains(input.Mnumber.Trim()))
            .WhereIF(input.Mstatus>0, u => u.Mstatus == input.Mstatus)
            .WhereIF(input.Tickets>0, u => u.Tickets == input.Tickets)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<OccupantAudit>((u, repair) => u.Repair == repair.Id )
            .LeftJoin<House>((u, repair, location) => u.location == location.Id )
            .LeftJoin<TwoCategories>((u, repair, location, tickets) => u.Tickets == tickets.Id )
            .LeftJoin<Employee>((u, repair, location, tickets, takers) => u.Takers == takers.Id )
            .Select((u, repair, location, tickets, takers) => new MaintenancesOutput
            {
                Id = u.Id,
                Mnumber = u.Mnumber,
                Mstatus = u.Mstatus,
                Mcategory = u.Mcategory,
                RepairTime = u.RepairTime,
                Dispatch = u.Dispatch,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                Repair = u.Repair, 
                RepairOccupantName = repair.OccupantName,
                location = u.location, 
                locationhouseName = location.houseName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                Tickets = u.Tickets, 
                TicketsTwoCategoriesName = tickets.TwoCategoriesName,
                Takers = u.Takers, 
                TakersEmployeeName = takers.EmployeeName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加报修管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加报修管理")]
    public async Task<long> Add(AddMaintenancesInput input)
    {
        var entity = input.Adapt<Maintenances>();
        await _maintenancesRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除报修管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除报修管理")]
    public async Task Delete(DeleteMaintenancesInput input)
    {
        var entity = await _maintenancesRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _maintenancesRep.FakeDeleteAsync(entity);   //假删除
        //await _maintenancesRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新报修管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新报修管理")]
    public async Task Update(UpdateMaintenancesInput input)
    {
        if (input.Mstatus == 0)
        {
            input.Mstatus = 1;
            
            var entity = input.Adapt<Maintenances>();
            await _maintenancesRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
        }
        if (input.Mstatus == 1)
        {
            input.Mstatus = 2;
            var entity = input.Adapt<Maintenances>();
            await _maintenancesRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
        }
       
    }

    /// <summary>
    /// 获取报修管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取报修管理")]
    public async Task<Maintenances> Detail([FromQuery] QueryByIdMaintenancesInput input)
    {
        return await _maintenancesRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取报修管理列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取报修管理列表")]
    public async Task<List<MaintenancesOutput>> List([FromQuery] PageMaintenancesInput input)
    {
        return await _maintenancesRep.AsQueryable().Select<MaintenancesOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取报修人列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "OccupantAuditRepairDropdown"), HttpGet]
    [DisplayName("获取报修人列表")]
    public async Task<dynamic> OccupantAuditRepairDropdown()
    {
        return await _maintenancesRep.Context.Queryable<OccupantAudit>()
                .Select(u => new
                {
                    Label = u.OccupantName,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取报修位置列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "HouselocationDropdown"), HttpGet]
    [DisplayName("获取报修位置列表")]
    public async Task<dynamic> HouselocationDropdown()
    {
        return await _maintenancesRep.Context.Queryable<House>()
                .Select(u => new
                {
                    Label = u.houseName,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取工单类别列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "TwoCategoriesTicketsDropdown"), HttpGet]
    [DisplayName("获取工单类别列表")]
    public async Task<dynamic> TwoCategoriesTicketsDropdown()
    {
        return await _maintenancesRep.Context.Queryable<TwoCategories>()
                .Select(u => new
                {
                    Label = u.TwoCategoriesName,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取接单人列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "EmployeeTakersDropdown"), HttpGet]
    [DisplayName("获取接单人列表")]
    public async Task<dynamic> EmployeeTakersDropdown()
    {
        return await _maintenancesRep.Context.Queryable<Employee>()
                .Select(u => new
                {
                    Label = u.EmployeeName,
                    Value = u.Id
                }
                ).ToListAsync();
    }




}
